<?php
/**
 * WebSocket.php
 *
 * @package reepu.com
 * @version {$Id$}
 * @copyright 2009-2018 Shanghai Reepu Information Tech. Co., Ltd.
 * @license Commercial
 * @author Boolean since.
 * @datetime 2018-12-10 22:53
 * =================================================================
 * 版权所有 (C) 2009-2018 Reepu.com，并保留所有权利。
 * 网站地址:http://www.reepu.com/
 * -----------------------------------------------------------------
 * 您只能在不用于商业目的的前提下对程序代码进行修改和使用；
 * 不允许对程序代码以任何形式任何目的的再发布。
 * =================================================================
 */

namespace Reepu\Phalcon\Swoole;

use Swoole;
use Phalcon;

class WebSocket extends Phalcon\Cli\Task
{
    public $handler = [];
    protected $server = null;

    public function onConstruct()
    {
        $usage = new Usage();
        $usage->check(['swoole', 'phalcon']);

        $this->initialize();
    }

    public function initialize()
    {
        $host = isset($this->swoole->websocket->host) ? $this->swoole->websocket->host : '0.0.0.0';
        $port = isset($this->swoole->websocket->port) ? $this->swoole->websocket->port : '9502';

        $this->server = new Swoole\Http\Server($host, $port);
    }

    /**
     * 启动服务
     * @param array $params -d 守护进程启动
     */
    public function startAction(array $params = [])
    {
        try {
            // 打印服务信息
            $this->printInfo();

            $dispatch_mode = (isset($params[0]) && '-d' == strtolower($params[0])) ? 1 : 0;
            $this->server->set(array_merge($this->swoole->setting->toArray(), ['dispatch_mode' => $dispatch_mode]));

            $_handler = null;
            $this->server->on('open', function (Swoole\WebSocket\Server $server, Swoole\Http\Request $request) use (&$_handler) {
                $path_info = trim($request->server['path_info'], '/');
                if (isset($this->handler[$path_info])) {
                    $_handler = $this->handler[$path_info]->open($server, $request);
                } else {
                    echo 'notfound handler to open';
                }
            });

            $this->server->on('message', function (Swoole\WebSocket\Server $server, Swoole\WebSocket\Frame $frame) use (&$_handler) {
                $_handler->message($server, $frame);
            });

            $this->server->on('close', function (Swoole\WebSocket\Server $server, int $fd, int $reactor_id) use (&$_handler) {
                $_handler->close($server, $fd, $reactor_id);
            });

            $this->server->start(); // 启动服务
        } catch (\Exception $e) {
            echo $e->getMessage();
        }
    }
}